package com.example.rule.expression;

import com.example.rule.db.entity.PymtRule;
import com.example.rule.db.entity.PymtRuleOperator;
import com.example.rule.core.Representation;
import com.example.rule.util.CacheUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author Jason - Chusifeng
 * @version 1.0.0
 * @className TodayExpression.java
 * @packageName com.example.rule.expression
 * @createTime 2022年10月12日 09:25:43
 * @description 可以创建日平均/日转账次数/日转账总金额的表达式
 */
public class TodayRepresentation implements Representation {

    private static final String EXPRESSION_FIELD = "total";

    private static final String EXPRESSION_FIELD_1 = "times";

    private static final String EXPRESSION_FIELD_2 = "dailyAverage";

    /**
     * @param rule 数据库保存的一条录入规则
     * @return expression 数组
     * @author Jason - Chusifeng
     * @Description
     * @version: v1.8.0
     * @date 14:17 2022/10/10
     **/
    public String[] createExpressions(PymtRule rule) {
        List<PymtRuleOperator> operatorList = CacheUtil.getRuleOperators();
        StringBuilder sb = new StringBuilder();
        Integer ruleType = rule.getType();
        sb.append(getExpressionField(ruleType));
        sb.append(getOpe(rule.getOperator1(), operatorList)).append(rule.getValue1());
        sb.append(",");
        //operator2
        String operator = rule.getOperator2();
        if (StringUtils.isNotBlank(operator)) {
            sb.append(getExpressionField(ruleType));
            sb.append(getOpe(operator, operatorList)).append(rule.getValue2());
        }
        sb.append(",");
        //operator3
        operator = rule.getOperator3();
        if (StringUtils.isNotBlank(operator)) {
            sb.append(getExpressionField(ruleType));
            sb.append(getOpe(operator, operatorList)).append(rule.getValue3());
        }
        return sb.toString().split(",");
    }

    private static String getOpe(String name, List<PymtRuleOperator> operatorList) {
        PymtRuleOperator ruleOperator = operatorList.stream().filter(op -> op.getPkPymtRuleOperator().equals(Integer.valueOf(name))).findFirst().orElseThrow(() -> new RuntimeException("don't get operator"));
        return ruleOperator.getValue();
    }

    private static String getExpressionField(Integer ruleType) {
        String field;
        switch (ruleType) {
            case 1:
                field = EXPRESSION_FIELD;
                break;
            case 2:
                field = EXPRESSION_FIELD_1;
                break;
            case 7:
                field = EXPRESSION_FIELD_2;
                break;
            default:
                field = null;
        }
        return field;
    }
}
